import { getProfile } from '@/http'
import NProgress from './nprogress'
import { useUserStore } from '@/stores'
import { ROUTER_WHITELIST } from '@/config'

const modules = import.meta.glob('@/views/**/*View.vue')

export const getImportComponent = (path) => {
  return modules[`/src/views/${path}.vue`]
}

const routes = [
  {
    path: 'home',
    name: 'home',
    component: getImportComponent('home/HomeView'),
    meta: {
      permissions: []
    }
  },
  {
    path: 'role',
    name: 'role',
    component: getImportComponent('role/RoleView'),
    meta: {
      permissions: []
    }
  },
  {
    path: 'role/save',
    name: 'role-save',
    component: getImportComponent('role/SaveView'),
    meta: {
      permissions: []
    }
  },
  {
    path: 'user',
    name: 'user',
    component: getImportComponent('user/UserView'),
    meta: {
      permissions: []
    }
  },
  {
    path: 'user/save',
    name: 'user-save',
    component: getImportComponent('user/SaveView'),
    meta: {
      permissions: []
    }
  },
  {
    path: 'user/add',
    name: 'user-add',
    component: getImportComponent('user/SaveView'),
    meta: {
      permissions: []
    }
  },
  {
    path: 'permission',
    name: 'permission',
    component: getImportComponent('permission/PermissionView'),
    meta: {
      permissions: []
    }
  },
  {
    path: 'permission/save',
    name: 'permission-save',
    component: getImportComponent('permission/SaveView'),
    meta: {
      permissions: []
    }
  }
]

/**
* 路由前置过滤器
* @param {{name: string, path: string}} to
* @returns {boolean | object} true-表示可跳转,false-表示不跳转,object-表示新跳转的路由对象
* @description
* isLogin - 是否已经登录
* isLoginView - 是否去往登录界面
* if (isLogin) {
   if (isLoginView) {
     // 登录 && 去往登录界面 => 已经登录的用户不需要去往登录界面
     return false
   } else {
     // 登录 && 没去往登录界面 => 已经登录的用户不需要去往登录界面，什么都可以不做
   }
 } else {
   if (isLoginView) {
     // 未登录 && 去往登录界面 => 没有登录的用户需要去往登录界面，什么都可以不做
   } else {
     // 未登录 && 没去往登录界面 => 没有登录的用户需要去往登录界面，没去认证则重定向去认证
     return { name: 'Login' }
   }
 }
*/
export const onBefore = async (to) => {
  NProgress.start()

  if (ROUTER_WHITELIST.includes(to.name)) {
    return true
  }

  const userStore = useUserStore()
  const isLogin = userStore.isLogin()
  const isLoginView = to.name === 'login'
  if (!isLogin && isLoginView) {
    return true
  } else if (isLogin && isLoginView) {
    return { name: 'home' }
  } else if (!isLogin && !isLoginView) {
    return { name: 'login' }
  }

  const profile = await getProfile()
  if (profile.root) {
    return true
  }
  const oldPerms = userStore.permissions
  const newPerms = profile.permissions

  // newPerms - oldPerms = 需要新增权限
  const addPerms = newPerms.filter((p) => !oldPerms.includes(p))
  // oldPerms - newPerms = 需要删除权限
  const remPerms = oldPerms.filter((p) => !newPerms.includes(p))
  const updated = addPerms.length > 0 || remPerms.length > 0
  // 更新
  userStore.permissions = newPerms
  if (updated) {
    // 先删除，后新增，这样 permissions 数组就不会漏掉
    if (remPerms.length > 0) {
      routes
        .filter((route) =>
          remPerms.find((permission) => route?.meta?.permissions?.includes(permission))
        )
        .forEach((route) => this.removeRoute(route.name))
    }

    if (addPerms.length > 0) {
      routes
        .filter((route) =>
          addPerms.find((permission) => route?.meta?.permissions?.includes(permission))
        )
        .forEach((route) => this.addRoute(route))
    }
    // 这里必须使用 path，因为这里才动态添加或者删除路由，可能已经匹配到 NotFound 路由了，只有 path 是正确的，重新跳转下就可以了
    return { path: to.path, replace: true }
  }

  if (!to?.meta?.permissions?.find((u) => newPerms.includes(u))) {
    console.error('路由跳转无权限')
    // false 表示不跳转
    return false
  }

  return true
}

export const onError = (error) => {
  NProgress.done()
  console.error('路由错误', error.message)
}

export const onAfter = () => {
  NProgress.done()
}
